/**
 * Created by zhangjinrui on 17/6/27.
 */

public class Solution393 {

    public static void main(String args[]) {
        Solution393 s = new Solution393();
        System.out.println(s.validUtf8(new int[]{145}));
//        System.out.println(Integer.toBinaryString(145));
    }

    public boolean validUtf8(int[] data) {
        int len = 0;
        int idx = 0;
        while (idx < data.length) {
            if (len == 0) {
                len = getLen(data[idx++]);
                if (len == -1 || len == 1) {
                    return false;
                }
                if(len > 0){
                    len --;
                }
            } else {
                if (satisfy(data[idx++])) {
                    len--;
                } else {
                    return false;
                }
            }
        }
        return len == 0;
    }

    public int getLen(int a) {
        if(((a >> 7) & 1) == 0){
            return 0;
        }
        a = a & ((1 << 8) - 1);
        int ret = 0;
        for (int i = 7; i >= 3; i--) {
            if (((a >> i) & 1) == 1) {
                ret++;
            } else {
                return ret;
            }
        }
        return -1;
    }

    public boolean satisfy(int a) {
        if (((a >> 7) & 1) == 1 && ((a >> 6) & 1) == 0) {
            return true;
        }
        return false;
    }
}
